const net = require('net');
const fs = require('fs');

const server = net.createServer((socket) => {
    console.log('Client connected');

    socket.on('data', (data) => {
        const timestamp = new Date().toISOString();
        const clientAddress = `${socket.remoteAddress}:${socket.remotePort}`;
        const formattedData = `【${timestamp}-${clientAddress}】: ${data.toString()}\n\n`;

        console.log('Received data:', formattedData);

        // 将处理后的数据写入到文本文件中
        fs.appendFile('received_data.txt', formattedData, (err) => {
            if (err) {
                console.error('Error writing to file:', err);
            } else {
                console.log('Data written to file');
            }
        });

        // 延迟3秒后发送响应字符串给客户端
        setTimeout(() => {
            const responseString = 'Delayed response after 3 seconds. Thank you!';
            socket.write(responseString);
        }, 1000);
    });

    socket.on('end', () => {
        console.log('Client disconnected');
    });
});

const PORT = 12345;

server.listen(PORT, () => {
    console.log(`TCP server running on port ${PORT}`);
});
